import { deleteCart } from '@/services/chdstore';
import { DeleteOutlined, ReloadOutlined } from '@ant-design/icons';
import type {
  ActionType,
  EditableFormInstance,
  ProColumns,
} from '@ant-design/pro-components';
import { EditableProTable } from '@ant-design/pro-components';
import { Button, Flex, Image, message, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import styles from './index.less';

export default (props) => {
  const { init, data, loading, setLoading, type = '', goodsData = {} } = props;
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() => []);
  const actionRef = useRef<ActionType>();
  const editableFormRef = useRef<EditableFormInstance>();

  // 删除
  const onRemove = (id) => {
    setLoading(true);
    deleteCart(id).finally(() => {
      init();
    });
  };

  // 清空购物车
  const onClear = () => {
    if (!data.shoppingList || data.shoppingList.length === 0) {
      message.error('购物车为空');
    }
    setLoading(true);
    Promise.all(data.shoppingList.map((item) => deleteCart(item.id))).finally(
      () => {
        init();
      },
    );
  };

  useEffect(() => {
    init();
  }, []);

  const columns: ProColumns<any>[] = [
    {
      title: '商品',
      dataIndex: 'associate',
      valueType: 'select',
      width: 200,
      render(_, row) {
        return (
          <Space>
            <Image src={row.pic} width={64} height={64}></Image>
            <div>{row.name}</div>
          </Space>
        );
      },
    },
    {
      title: '价格',
      dataIndex: 'price',
      valueType: 'text',
      readonly: true,
      width: 100,
      render(_) {
        return _ + '点券';
      },
    },
    {
      title: '数量',
      dataIndex: 'num',
      valueType: 'digit',
      width: 100,
    },
    {
      title: '合计',
      dataIndex: 'amount',
      valueType: 'text',
      readonly: true,
      width: 120,
      render(_) {
        return _ + '点券';
      },
    },
  ];

  if (type !== 'modal') {
    columns.push({
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (_, row) => [
        <Button
          key="delete"
          type="link"
          onClick={() => {
            onRemove(row.id);
          }}
        >
          删除
        </Button>,
      ],
    });
  }

  return (
    <>
      <EditableProTable
        loading={loading}
        rowKey="id"
        editableFormRef={editableFormRef}
        actionRef={actionRef}
        columns={columns}
        value={data.shoppingList}
        recordCreatorProps={false}
        editable={{
          type: 'multiple',
          editableKeys,
          onChange: (key) => {
            setEditableRowKeys(key);
          },
        }}
        toolBarRender={() => {
          if (type === 'modal') {
            return [];
          }
          return [
            <Button key="reload" onClick={init} icon={<ReloadOutlined />}>
              刷新购物车
            </Button>,
            <Button key="delete" onClick={onClear} icon={<DeleteOutlined />}>
              清空购物车
            </Button>,
          ];
        }}
        footer={() => {
          return (
            <Flex justify="space-between">
              <div
                className={styles.footer}
                dangerouslySetInnerHTML={{
                  __html: data.billingInformation,
                }}
              ></div>
            </Flex>
          );
        }}
      />
      {type === 'modal' && (
        <Flex vertical gap={6}>
          <div>购物车总价：{goodsData.totalPrice}点券</div>
          <div>消费物品：{goodsData.goodsName}</div>
          <div>消费次数：{goodsData.goodsNum}</div>
        </Flex>
      )}
    </>
  );
};
